import * as Koa from 'koa';
import { getRoles, delRole, addRole, updateRole, searchRoleTotalNumbers } from "../entity/role";
import { joinDefaultFields } from '../utils';
import dayjs = require('dayjs');
// TODO：commonjs 模式下引用 esmodule 模块
let nanoid: any = null;
(async () => {
  nanoid = (await eval("import('nanoid')")).nanoid;
})();

const errorMsg = `服务器错误：${'role'}`;
const successMsg = `成功：${'role'}`;

export default class RoleService {
  getRoles = async (ctx: Koa.Context) => {
    try {
      const params = ctx.request.body;
      const { rid, name, pageNumber, pageSize } = params || {}; // 查询条件
      if (!pageNumber || !pageSize) return ctx.fail(null, "pageNumber、pageSize不能为空", -1);
      // 相等的条件
      let condition = "";
      let equals: string | string[] = [];
      rid && (equals.push(` rid = "${rid}"`));
      name && (equals.push(` name = "${name}"`));
      equals = equals.join(" AND");
      equals && (condition += `WHERE ${equals}`);
      // 分页的条件
      condition += ` LIMIT ${pageSize} OFFSET ${(pageNumber - 1) * pageSize}`;
      const result: any = await getRoles(ctx, { condition }, { needRoleName: true });
      const resultNums: any = await searchRoleTotalNumbers(ctx);

      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success({
          list: result.data || [],
          total: resultNums?.data || 0,
          pageNumber: pageNumber,
          pageSize: pageSize,
        }, successMsg);
      }
    } catch (error) {
      ctx.fail(null, error, -1);
    }
  };

  delRole = async (ctx: Koa.Context) => {
    try {
      const { rid } = ctx.request.body;
      if (!rid || !rid.length) return ctx.fail(null, "uid不能为空", -1);
      const rids = Array.isArray(rid)? rid : [rid];
      let condition = `rid IN (${rids.map((i) => `"${i}"`).join(",")})`;
      const result: any =  !!rids.length && await delRole(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  addRole = async (ctx: Koa.Context) => {
    try {
      const roleInfo = ctx.request.body;
      const _roleInfo = joinDefaultFields(roleInfo, "roleFields");
      _roleInfo.rid = nanoid(18);
      _roleInfo.create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      const result: any = _roleInfo && await addRole(ctx, _roleInfo);
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg ||errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  updateRole = async (ctx: Koa.Context) => {
    try {
      const roleInfo = ctx.request.body;
      roleInfo.update_time = dayjs().format("YYYY-MM-DD HH:mm:ss"); // 最后的更新时间
      const result: any = roleInfo && await updateRole(ctx, roleInfo);
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };
}
